/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * VisConsultaCertificados.java
 *
 * Created on 18/02/2011, 02:48:47 PM
 */
package coladas;

import java.util.ArrayList;
import javax.swing.ButtonGroup;
import javax.swing.DefaultListSelectionModel;
import javax.swing.table.DefaultTableModel;

/*Inicio*/
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;

import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.swing.JOptionPane;
/*Fin*/
/**
 *
 * @author cbazan
 */
public class VisConsultaCertificados extends javax.swing.JFrame {

    Operario ope;
    private DefaultTableModel mdlVista1;

    /** Creates new form VisConsultaCertificados */
    public VisConsultaCertificados(Operario _ope) {
        initComponents();
        ope = _ope;
        mdlVista1 = (DefaultTableModel) jTb_Vista1.getModel();
        jTb_Vista1.setSelectionMode(DefaultListSelectionModel.SINGLE_SELECTION);

        ButtonGroup grupoDeBotones = new ButtonGroup();
        grupoDeBotones.add(jR_colada);
        grupoDeBotones.add(jR_pedido);



    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        buttonGroup2 = new javax.swing.ButtonGroup();
        buttonGroup3 = new javax.swing.ButtonGroup();
        buttonGroup4 = new javax.swing.ButtonGroup();
        buttonGroup5 = new javax.swing.ButtonGroup();
        jPanel1 = new javax.swing.JPanel();
        jR_colada = new javax.swing.JRadioButton();
        jR_pedido = new javax.swing.JRadioButton();
        jTxt_Colada = new javax.swing.JTextField();
        jTxt_numPedido = new javax.swing.JTextField();
        jBBuscar = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTb_Vista1 = new javax.swing.JTable();
        jbSalir = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jR_colada.setText("Nro Colada");

        jR_pedido.setText("Pedido");

        jBBuscar.setText("Buscar");
        jBBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBBuscarActionPerformed(evt);
            }
        });

        jLabel1.setText("CONSULTA CERTIFICADO DE CALIDAD");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(28, 28, 28)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jR_pedido)
                            .addComponent(jR_colada))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jTxt_numPedido, javax.swing.GroupLayout.DEFAULT_SIZE, 306, Short.MAX_VALUE)
                            .addComponent(jTxt_Colada, javax.swing.GroupLayout.DEFAULT_SIZE, 306, Short.MAX_VALUE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel1)))
                .addGap(18, 18, 18)
                .addComponent(jBBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(7, 7, 7)
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jTxt_Colada, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jR_colada))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jTxt_numPedido, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jR_pedido)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(29, 29, 29)
                        .addComponent(jBBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jTb_Vista1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Pedido", "Certificado", "Colada", "Ruta en Disco"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.Object.class, java.lang.String.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jTb_Vista1);

        jbSalir.setText("Salir");
        jbSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbSalirActionPerformed(evt);
            }
        });

        jButton1.setText("Enviar Mail");
        jButton1.setActionCommand("jbtnEnviar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 529, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addGap(154, 154, 154)
                        .addComponent(jbSalir, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jbSalir, javax.swing.GroupLayout.DEFAULT_SIZE, 38, Short.MAX_VALUE)
                    .addComponent(jButton1))
                .addGap(18, 18, 18))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jBBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBBuscarActionPerformed

        for (int i = 0; i < mdlVista1.getRowCount(); i++) {
            mdlVista1.removeRow(i);
            mdlVista1.fireTableRowsDeleted(i, i);
        }


        if (jR_pedido.isSelected()) {
            //ArrayList<ClsVista1> resultado = ope.BuscarCertificado_x_NumPedido(jTxt_numPedido.getText());
            Pedido objPedido = ope.BuscarPedido(jTxt_numPedido.getText());
            ArrayList<Certificado> listaCertificado = objPedido.getCertificados();

           int tam=0;
            for(int i=0; i<listaCertificado.size();i++)
            {
                Certificado objCertificado = listaCertificado.get(i);
                ArrayList<Colada> listaColada=objCertificado.getColadas();
                tam = tam + listaColada.size();
            }
           mdlVista1.setRowCount(tam);
            int fila=0;
            for(int i=0; i<listaCertificado.size();i++)
            {
                Certificado objCertificado = listaCertificado.get(i);
                ArrayList<Colada> listaColada=objCertificado.getColadas();               
                
                for(int j=0;j<listaColada.size();j++)
                {
                    Colada objColada = listaColada.get(j);

                mdlVista1.setValueAt(objColada.getNroPedido(), fila, 0);
                mdlVista1.setValueAt(objCertificado.getCodCerti(), fila, 1);
                mdlVista1.setValueAt(objColada.getCodColada(), fila, 2);
                mdlVista1.setValueAt(objCertificado.getRutCerti(), fila, 3);

                fila++;
                }

            }

          //  
            
            
        }

        if (jR_colada.isSelected()) {
            ArrayList<ClsVista1> resultado = ope.BuscarCertificado_x_NumColada(jTxt_Colada.getText());
            mdlVista1.setRowCount(resultado.size());
            
            for (int i = 0; i < resultado.size(); i++) {
                ClsVista1 v1 = resultado.get(i);
                mdlVista1.setValueAt(v1.getPedido(), i, 0);
                mdlVista1.setValueAt(v1.getCertificado(), i, 1);
                mdlVista1.setValueAt(v1.getColada(), i, 2);
                mdlVista1.setValueAt(v1.getRuta(), i, 3);
            }
        }
}//GEN-LAST:event_jBBuscarActionPerformed

    private void jbSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbSalirActionPerformed
        // TODO add your handling code here:

        this.setVisible(false);
}//GEN-LAST:event_jbSalirActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
try
        {


           // String strRutaImagen = "F:\\YURY\\FELIX\\Aplicacion\\archivos\\java.png";
            String curDir = System.getProperty("user.dir");

             int fila = jTb_Vista1.getSelectedRow();

            if (fila!=-1)
            {
                String strRutaImagen;
                String strNombreArchivo;

                if(mdlVista1.getValueAt(fila, 3)!=null)
                {
                    strRutaImagen = mdlVista1.getValueAt(fila, 3).toString();
                    strNombreArchivo = strRutaImagen.substring(strRutaImagen.lastIndexOf("\\")+1,strRutaImagen.length());
                    String strCorreoEnvio  = JOptionPane.showInputDialog(rootPane, "Ingrese cuenta de Correo").toString();

                    if(enviarMail(strRutaImagen,strNombreArchivo,strCorreoEnvio))
                    {
                        JOptionPane.showMessageDialog(rootPane, "Envio de Correo satisfactorio");
                    }
                    else
                    {
                        JOptionPane.showMessageDialog(rootPane, "Error en Envio de Correo ");

                    }

                }
                else
                {
                    JOptionPane.showMessageDialog(rootPane, "No Contiene una ruta de Certificado");
                }




            }
            else
            {
                JOptionPane.showMessageDialog(rootPane, "Debe seleccionar un registro.");
                  //  JOptionPane.showMessageDialog(rootPane, curDir);

            }


        }
        catch (Exception e)
        {
            e.printStackTrace();
        }        // TODO add your handling code here:

    }//GEN-LAST:event_jButton1ActionPerformed

    public boolean enviarMail(String strRutaImagen,String strNombreArchivo,String strCorreoEnvio)
{
 // se obtiene el objeto Session. La configuración es para
          // una cuenta de gmail.
    boolean estadoEnvio = false;
          try
          {
            Properties props = new Properties();
            props.put("mail.smtp.host", "smtp.gmail.com");
            props.setProperty("mail.smtp.starttls.enable", "true");
            props.setProperty("mail.smtp.port", "587");
            props.setProperty("mail.smtp.user", "fcabrejosll@gmail.com");
            props.setProperty("mail.smtp.auth", "true");

            Session session = Session.getDefaultInstance(props, null);
            // session.setDebug(true);

            // Se compone la parte del texto
            BodyPart texto = new MimeBodyPart();
            texto.setText("<b>Sres se adjunta certificado</b>");

            // Se compone el adjunto con la imagen
            BodyPart adjunto = new MimeBodyPart();
            adjunto.setDataHandler(
                new DataHandler(new FileDataSource(strRutaImagen)));
            adjunto.setFileName(strNombreArchivo);

            // Una MultiParte para agrupar texto e imagen.
            MimeMultipart multiParte = new MimeMultipart();
            multiParte.addBodyPart(texto);
            multiParte.addBodyPart(adjunto);

            // Se compone el correo, dando to, from, subject y el
            // contenido.
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress("administrador@gmail.com"));
            message.addRecipient(
                Message.RecipientType.TO,
                new InternetAddress(strCorreoEnvio));
            message.setSubject("Certificados");
            message.setContent(multiParte);

            // Se envia el correo.
            Transport t = session.getTransport("smtp");
            t.connect("fcabrejosll@gmail.com", "ndnqtcysce");
            t.sendMessage(message, message.getAllRecipients());
            t.close();

            estadoEnvio=true;


        }
          catch(Exception e)
          {
            e.printStackTrace();
            estadoEnvio=false;
          }

          return estadoEnvio;

}


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.ButtonGroup buttonGroup2;
    private javax.swing.ButtonGroup buttonGroup3;
    private javax.swing.ButtonGroup buttonGroup4;
    private javax.swing.ButtonGroup buttonGroup5;
    private javax.swing.JButton jBBuscar;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JRadioButton jR_colada;
    private javax.swing.JRadioButton jR_pedido;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTb_Vista1;
    private javax.swing.JTextField jTxt_Colada;
    private javax.swing.JTextField jTxt_numPedido;
    private javax.swing.JButton jbSalir;
    // End of variables declaration//GEN-END:variables
}
